﻿using CleanArchitecture.Core.Events;
using CleanArchitecture.Core.Interfaces;
using CleanArchitecture.Infrastructure.Entities.Customers;
using CleanArchitecture.Infrastructure.Interfaces;
using CleanArchitecture.Infrastructure.Interfaces.Customers;
using System;
using System.Linq;

namespace CleanArchitecture.Infrastructure.Services.Customers
{
    public partial class CustomerService : ICustomerService
    {
        #region Fields
        private readonly IDomainEventDispatcher _eventDispatcher;
        private readonly IRepository<Customer> _customerRepository;
        #endregion

        #region Ctor
        public CustomerService(IDomainEventDispatcher eventDispatcher,
            IRepository<Customer> customerRepo)
        {
            this._eventDispatcher = eventDispatcher;
            this._customerRepository = customerRepo;
        }
        #endregion

        #region Methods
        public virtual Customer GetCustomerById(int cid)
        {
            if (cid <= 0) return null;
            return _customerRepository.GetById(cid);
        }

        public virtual Customer GetCustomerByMobile(string mobile)
        {
            if (string.IsNullOrEmpty(mobile))
                return null;
            return _customerRepository.Table.FirstOrDefault(c => c.Mobile == mobile);
        }

        public virtual Customer GetCustomerByEmail(string email)
        {
            if (string.IsNullOrEmpty(email))
                return null;
            return _customerRepository.Table.FirstOrDefault(c => c.Email == email);
        }

        public virtual Customer GetCustomerByLoginname(string loginname)
        {
            if (string.IsNullOrEmpty(loginname))
                return null;
            return _customerRepository.Table.FirstOrDefault(c => c.CustomerLoginname == loginname);
        }
        public virtual void UpdateCustomer(Customer entity)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));

            _customerRepository.Update(entity, new string[] { nameof(entity.CreatedOnTimeUtc) });

            //event notification
            if (!string.IsNullOrEmpty(entity.SysLogMsg))
                _eventDispatcher.Dispatch(new EntityUpdatedEvent<Customer>(entity));
        }
        #endregion
    }
}
